import { ApiService } from "./index";
import type {
  KnowledgeBase,
  KnowledgeDocument,
  KnowledgeChunk,
  KnowledgeQuery,
  KnowledgeSearchResult,
  KnowledgeStats,
  DocumentMetadata,
  VectorSearchParams,
  KnowledgeCategory,
  KnowledgeTag,
} from "@/types/knowledge";

class KnowledgeApiService extends ApiService {
  // 知识库管理
  async getKnowledgeBases(params?: {
    page?: number;
    limit?: number;
    search?: string;
    category?: string;
    status?: "active" | "inactive" | "processing";
    sortBy?: "name" | "createdAt" | "updatedAt" | "documentCount";
    sortOrder?: "asc" | "desc";
  }) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.search) queryParams.append("search", params.search);
    if (params?.category) queryParams.append("category", params.category);
    if (params?.status) queryParams.append("status", params.status);
    if (params?.sortBy) queryParams.append("sortBy", params.sortBy);
    if (params?.sortOrder) queryParams.append("sortOrder", params.sortOrder);

    const url = `/knowledge/bases${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      knowledgeBases: KnowledgeBase[];
      total: number;
      page: number;
      totalPages: number;
    }>(url);
  }

  async getKnowledgeBase(baseId: string) {
    return this.get<KnowledgeBase>(`/knowledge/bases/${baseId}`);
  }

  async createKnowledgeBase(data: {
    name: string;
    description?: string;
    category?: string;
    tags?: string[];
    isPublic?: boolean;
    settings?: {
      chunkSize?: number;
      chunkOverlap?: number;
      embeddingModel?: string;
      indexingStrategy?: "auto" | "manual";
      autoUpdate?: boolean;
    };
  }) {
    return this.post<KnowledgeBase>("/knowledge/bases", data);
  }

  async updateKnowledgeBase(
    baseId: string,
    data: Partial<{
      name: string;
      description: string;
      category: string;
      tags: string[];
      isPublic: boolean;
      settings: Record<string, any>;
    }>,
  ) {
    return this.put<KnowledgeBase>(`/knowledge/bases/${baseId}`, data);
  }

  async deleteKnowledgeBase(baseId: string) {
    return this.delete(`/knowledge/bases/${baseId}`);
  }

  async duplicateKnowledgeBase(
    baseId: string,
    data: {
      name: string;
      includeDocuments?: boolean;
    },
  ) {
    return this.post<KnowledgeBase>(
      `/knowledge/bases/${baseId}/duplicate`,
      data,
    );
  }

  // 文档管理
  async getDocuments(
    baseId: string,
    params?: {
      page?: number;
      limit?: number;
      search?: string;
      type?: "text" | "pdf" | "docx" | "html" | "markdown";
      status?: "pending" | "processing" | "completed" | "failed";
      sortBy?: "name" | "createdAt" | "updatedAt" | "size";
      sortOrder?: "asc" | "desc";
    },
  ) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.search) queryParams.append("search", params.search);
    if (params?.type) queryParams.append("type", params.type);
    if (params?.status) queryParams.append("status", params.status);
    if (params?.sortBy) queryParams.append("sortBy", params.sortBy);
    if (params?.sortOrder) queryParams.append("sortOrder", params.sortOrder);

    const url = `/knowledge/bases/${baseId}/documents${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      documents: KnowledgeDocument[];
      total: number;
      page: number;
      totalPages: number;
    }>(url);
  }

  async getDocument(baseId: string, documentId: string) {
    return this.get<KnowledgeDocument>(
      `/knowledge/bases/${baseId}/documents/${documentId}`,
    );
  }

  async uploadDocument(
    baseId: string,
    file: File,
    metadata?: DocumentMetadata,
  ) {
    const formData = new FormData();
    formData.append("file", file);
    if (metadata) {
      formData.append("metadata", JSON.stringify(metadata));
    }

    return this.upload<KnowledgeDocument>(
      `/knowledge/bases/${baseId}/documents/upload`,
      formData,
    );
  }

  async createTextDocument(
    baseId: string,
    data: {
      title: string;
      content: string;
      metadata?: DocumentMetadata;
    },
  ) {
    return this.post<KnowledgeDocument>(
      `/knowledge/bases/${baseId}/documents`,
      data,
    );
  }

  async updateDocument(
    baseId: string,
    documentId: string,
    data: {
      title?: string;
      content?: string;
      metadata?: DocumentMetadata;
    },
  ) {
    return this.put<KnowledgeDocument>(
      `/knowledge/bases/${baseId}/documents/${documentId}`,
      data,
    );
  }

  async deleteDocument(baseId: string, documentId: string) {
    return this.delete(`/knowledge/bases/${baseId}/documents/${documentId}`);
  }

  async reprocessDocument(baseId: string, documentId: string) {
    return this.post(
      `/knowledge/bases/${baseId}/documents/${documentId}/reprocess`,
    );
  }

  async getDocumentChunks(
    baseId: string,
    documentId: string,
    params?: {
      page?: number;
      limit?: number;
    },
  ) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());

    const url = `/knowledge/bases/${baseId}/documents/${documentId}/chunks${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      chunks: KnowledgeChunk[];
      total: number;
      page: number;
      totalPages: number;
    }>(url);
  }

  // 批量操作
  async bulkUploadDocuments(
    baseId: string,
    files: File[],
    metadata?: DocumentMetadata[],
  ) {
    const formData = new FormData();
    files.forEach((file, index) => {
      formData.append(`files`, file);
      if (metadata?.[index]) {
        formData.append(`metadata_${index}`, JSON.stringify(metadata[index]));
      }
    });

    return this.upload<{
      successful: KnowledgeDocument[];
      failed: Array<{ filename: string; error: string }>;
    }>(`/knowledge/bases/${baseId}/documents/bulk-upload`, formData);
  }

  async bulkDeleteDocuments(baseId: string, documentIds: string[]) {
    return this.post(`/knowledge/bases/${baseId}/documents/bulk-delete`, {
      documentIds,
    });
  }

  async bulkReprocessDocuments(baseId: string, documentIds: string[]) {
    return this.post(`/knowledge/bases/${baseId}/documents/bulk-reprocess`, {
      documentIds,
    });
  }

  // 搜索功能
  async searchKnowledge(query: KnowledgeQuery) {
    return this.post<KnowledgeSearchResult>("/knowledge/search", query);
  }

  async vectorSearch(params: VectorSearchParams) {
    return this.post<{
      results: Array<{
        chunk: KnowledgeChunk;
        score: number;
        document: KnowledgeDocument;
        knowledgeBase: KnowledgeBase;
      }>;
      total: number;
      queryTime: number;
    }>("/knowledge/vector-search", params);
  }

  async semanticSearch(
    baseId: string,
    query: string,
    params?: {
      limit?: number;
      threshold?: number;
      includeMetadata?: boolean;
    },
  ) {
    return this.post<{
      results: Array<{
        chunk: KnowledgeChunk;
        score: number;
        document: KnowledgeDocument;
        highlights?: string[];
      }>;
      total: number;
      queryTime: number;
    }>(`/knowledge/bases/${baseId}/semantic-search`, {
      query,
      ...params,
    });
  }

  async hybridSearch(
    baseId: string,
    query: string,
    params?: {
      limit?: number;
      keywordWeight?: number;
      semanticWeight?: number;
      threshold?: number;
      filters?: Record<string, any>;
    },
  ) {
    return this.post<{
      results: Array<{
        chunk: KnowledgeChunk;
        score: number;
        keywordScore: number;
        semanticScore: number;
        document: KnowledgeDocument;
        highlights?: string[];
      }>;
      total: number;
      queryTime: number;
    }>(`/knowledge/bases/${baseId}/hybrid-search`, {
      query,
      ...params,
    });
  }

  // 问答功能
  async askQuestion(
    baseId: string,
    question: string,
    params?: {
      maxChunks?: number;
      temperature?: number;
      model?: string;
      includeSource?: boolean;
    },
  ) {
    return this.post<{
      answer: string;
      sources: Array<{
        chunk: KnowledgeChunk;
        document: KnowledgeDocument;
        relevanceScore: number;
      }>;
      confidence: number;
      responseTime: number;
    }>(`/knowledge/bases/${baseId}/ask`, {
      question,
      ...params,
    });
  }

  async getQuestionHistory(
    baseId: string,
    params?: {
      page?: number;
      limit?: number;
      userId?: string;
    },
  ) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.userId) queryParams.append("userId", params.userId);

    const url = `/knowledge/bases/${baseId}/questions${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      questions: Array<{
        id: string;
        question: string;
        answer: string;
        confidence: number;
        createdAt: string;
        userId?: string;
        sources: Array<{
          documentId: string;
          chunkId: string;
          relevanceScore: number;
        }>;
      }>;
      total: number;
      page: number;
      totalPages: number;
    }>(url);
  }

  // 统计分析
  async getKnowledgeStats(baseId: string) {
    return this.get<KnowledgeStats>(`/knowledge/bases/${baseId}/stats`);
  }

  async getSearchAnalytics(
    baseId: string,
    params?: {
      dateFrom?: string;
      dateTo?: string;
      groupBy?: "day" | "week" | "month";
    },
  ) {
    const queryParams = new URLSearchParams();
    if (params?.dateFrom) queryParams.append("dateFrom", params.dateFrom);
    if (params?.dateTo) queryParams.append("dateTo", params.dateTo);
    if (params?.groupBy) queryParams.append("groupBy", params.groupBy);

    const url = `/knowledge/bases/${baseId}/analytics${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      searchCount: Array<{ date: string; count: number }>;
      topQueries: Array<{ query: string; count: number }>;
      avgConfidence: number;
      avgResponseTime: number;
      successRate: number;
    }>(url);
  }

  async getDocumentAnalytics(baseId: string, documentId: string) {
    return this.get<{
      viewCount: number;
      searchCount: number;
      citationCount: number;
      avgRelevanceScore: number;
      topQueries: Array<{ query: string; count: number }>;
      performance: {
        processingTime: number;
        chunkCount: number;
        indexSize: number;
      };
    }>(`/knowledge/bases/${baseId}/documents/${documentId}/analytics`);
  }

  // 分类和标签
  async getCategories() {
    return this.get<KnowledgeCategory[]>("/knowledge/categories");
  }

  async createCategory(data: {
    name: string;
    description?: string;
    color?: string;
    parentId?: string;
  }) {
    return this.post<KnowledgeCategory>("/knowledge/categories", data);
  }

  async updateCategory(
    categoryId: string,
    data: Partial<{
      name: string;
      description: string;
      color: string;
      parentId: string;
    }>,
  ) {
    return this.put<KnowledgeCategory>(
      `/knowledge/categories/${categoryId}`,
      data,
    );
  }

  async deleteCategory(categoryId: string) {
    return this.delete(`/knowledge/categories/${categoryId}`);
  }

  async getTags(params?: { search?: string; limit?: number }) {
    const queryParams = new URLSearchParams();
    if (params?.search) queryParams.append("search", params.search);
    if (params?.limit) queryParams.append("limit", params.limit.toString());

    const url = `/knowledge/tags${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<KnowledgeTag[]>(url);
  }

  async createTag(data: {
    name: string;
    color?: string;
    description?: string;
  }) {
    return this.post<KnowledgeTag>("/knowledge/tags", data);
  }

  // 导入导出
  async exportKnowledgeBase(baseId: string, format: "json" | "csv" | "pdf") {
    return this.download(
      `/knowledge/bases/${baseId}/export?format=${format}`,
      `knowledge-base-${baseId}.${format}`,
    );
  }

  async importKnowledgeBase(
    file: File,
    options?: {
      mergeStrategy?: "replace" | "merge" | "skip";
      preserveIds?: boolean;
    },
  ) {
    const formData = new FormData();
    formData.append("file", file);
    if (options) {
      formData.append("options", JSON.stringify(options));
    }

    return this.upload<{
      knowledgeBase: KnowledgeBase;
      importedDocuments: number;
      skippedDocuments: number;
      errors: string[];
    }>("/knowledge/import", formData);
  }

  // 索引管理
  async rebuildIndex(baseId: string) {
    return this.post(`/knowledge/bases/${baseId}/rebuild-index`);
  }

  async getIndexStatus(baseId: string) {
    return this.get<{
      status: "idle" | "building" | "updating" | "error";
      progress: number;
      lastUpdated: string;
      documentsIndexed: number;
      totalDocuments: number;
      error?: string;
    }>(`/knowledge/bases/${baseId}/index-status`);
  }

  async optimizeIndex(baseId: string) {
    return this.post(`/knowledge/bases/${baseId}/optimize-index`);
  }

  // 权限管理
  async getKnowledgeBasePermissions(baseId: string) {
    return this.get<{
      owner: string;
      collaborators: Array<{
        userId: string;
        username: string;
        role: "viewer" | "editor" | "admin";
        addedAt: string;
      }>;
      isPublic: boolean;
      publicPermissions: "read" | "none";
    }>(`/knowledge/bases/${baseId}/permissions`);
  }

  async updateKnowledgeBasePermissions(
    baseId: string,
    data: {
      collaborators?: Array<{
        userId: string;
        role: "viewer" | "editor" | "admin";
      }>;
      isPublic?: boolean;
      publicPermissions?: "read" | "none";
    },
  ) {
    return this.put(`/knowledge/bases/${baseId}/permissions`, data);
  }

  async shareKnowledgeBase(
    baseId: string,
    data: {
      userIds?: string[];
      emails?: string[];
      role: "viewer" | "editor" | "admin";
      message?: string;
    },
  ) {
    return this.post(`/knowledge/bases/${baseId}/share`, data);
  }

  // 版本控制
  async getDocumentVersions(baseId: string, documentId: string) {
    return this.get<
      Array<{
        id: string;
        version: number;
        title: string;
        createdAt: string;
        createdBy: string;
        changes: string;
        size: number;
      }>
    >(`/knowledge/bases/${baseId}/documents/${documentId}/versions`);
  }

  async getDocumentVersion(
    baseId: string,
    documentId: string,
    versionId: string,
  ) {
    return this.get<KnowledgeDocument>(
      `/knowledge/bases/${baseId}/documents/${documentId}/versions/${versionId}`,
    );
  }

  async restoreDocumentVersion(
    baseId: string,
    documentId: string,
    versionId: string,
  ) {
    return this.post(
      `/knowledge/bases/${baseId}/documents/${documentId}/versions/${versionId}/restore`,
    );
  }

  async compareDocumentVersions(
    baseId: string,
    documentId: string,
    fromVersion: string,
    toVersion: string,
  ) {
    return this.get<{
      diff: string;
      changes: Array<{
        type: "added" | "removed" | "modified";
        content: string;
        lineNumber?: number;
      }>;
    }>(
      `/knowledge/bases/${baseId}/documents/${documentId}/versions/compare?from=${fromVersion}&to=${toVersion}`,
    );
  }
}

export const knowledgeApi = new KnowledgeApiService();
export default knowledgeApi;
